package com.seeyon.apps.kk.manager;

import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

import org.apache.axis2.AxisFault;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.seeyon.apps.kk.manager.datasync.AbstractDataSyncManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.bo.OrganizationMessage;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.bo.V3xOrgPost;
import com.seeyon.ctp.organization.bo.V3xOrgPrincipal;
import com.seeyon.ctp.organization.bo.V3xOrgRole;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.ctp.util.annotation.NeedlessCheckLogin;
import com.seeyon.kk.utils.HanyuPinyinFormatUtils;
import com.seeyon.kk.utils.MapToLowerCaseUtils;
import com.seeyon.kk.utils.ValueUtils;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.FormUtils;
import com.seeyon.v3x.services.form.bean.FormExport;

import jersey.repackaged.com.google.common.collect.Lists;
import nc.itf.ly_ext.webservice.isyncpro.ISyncProStub;
import nc.itf.ly_ext.webservice.isyncpro.ISyncProStub.SyncPro;
import nc.itf.ly_ext.webservice.isyncpro.ISyncProStub.SyncProResponse;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncDept;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncDeptResponse;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncFundPlan;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncFundPlanResponse;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncPosts;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncPostsResponse;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SysncPsn;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SysncPsnResponse;

@NeedlessCheckLogin
public class OrgSyncManagerImpl extends AbstractDataSyncManager {

	private static final Log log = LogFactory.getLog(OrgSyncManagerImpl.class);

	private FreemarkFlowManager freemarkFlowManager;

	public OrganizationMessage getOrganizationMessage() {
		return organizationMessage;
	}

	public void setOrganizationMessage(OrganizationMessage organizationMessage) {
		this.organizationMessage = organizationMessage;
	}

	public OrgManager getOrgManager() {
		return orgManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public OrgManagerDirect getOrgManagerDirect() {
		return orgManagerDirect;
	}

	public void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
		this.orgManagerDirect = orgManagerDirect;
	}

	private OrganizationMessage organizationMessage;

	private OrgManager orgManager;

	private OrgManagerDirect orgManagerDirect;

	ISyncServiceStub stub = null;

	private Long accountId = 670869647114347L; // 单位Id

	private Map<String, String> rsMap = new HashMap<>(); // 记录完成信息

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	/**
	 * 初始化数据同步接口
	 * @return
	 */
	private ISyncServiceStub getISyncServiceStub() {
		try {
			if (stub == null)
				stub = new ISyncServiceStub();
		} catch (AxisFault e) {
			log.info("NC 组织架构接口调用异常：" + e.getMessage());
		}
		return stub;
	}

	/**
	 * 会议系统组织架构初始化 只调用一次
	 * 
	 * @return
	 */
	public Map<String, String> orgTOMeeting() {
		rsMap.put("code", "1000");
		rsMap.put("message", "orgSync is ok!");
		initMeetingOrg();
		return rsMap;
	}
	
	public Map<String, String> orgMember(){
		if (!this.updateMember())
			return rsMap;
		if (!this.updatePost())
			return rsMap;
		return rsMap;
	}

	public Map<String, String> org() {
		rsMap.put("code", "1000");
		rsMap.put("message", "orgSync is ok!");
		this.initNCDept();
		this.initNCMember();
		this.initNCPost();
		if (!this.addDept())
			return rsMap;
		if (!this.updateDept())
			return rsMap;
		return rsMap;
	}

	public Map<String, String> orgSync() {
		rsMap.put("code", "1000");
		rsMap.put("message", "orgSync is ok!");
		this.initNCDept();
		this.initNCMember();
		this.initNCPost();
		if (!this.addDept())
			return rsMap;
		if (!this.updateDept())
			return rsMap;
		if (!this.addPost())
			return rsMap;
		if (!this.updatePost())
			return rsMap;
		if (!this.addMember())
			return rsMap;
		if (!this.updateMember())
			return rsMap;
		return rsMap;
	}

	/**
	 * NC部门数据添加到底表
	 */
	public void initNCDept() {
		try {
			SyncDept syncDept2 = new SyncDept();
			String maxDateSql = this.freemarkFlowManager
					.fltTemplateIntoString("datasync/orgsync/initsql/select_dept_maxdate.ftl", null);
			List<Map<String, Object>> maxDate = this.jdbcTemplate.queryForList(maxDateSql);
			if (!maxDate.isEmpty()) {
				Map<String, Object> maxDateMap = maxDate.get(0);
				Map<String, Object> par = new HashMap<>();
				par.put("ts", MapUtils.getString(maxDateMap, "ts"));
				syncDept2.setString(JSON.toJSONString(par));
			}
			SyncDeptResponse rs = getISyncServiceStub().syncDept(syncDept2);
			JSONObject jsonObject = JSONObject.parseObject(rs.get_return());
			JSONArray items = JSON.parseArray(jsonObject.getString("obj"));
			for (Object object : items) {
				Map<String, Object> map = (Map<String, Object>) object;
				List<Map<String, Object>> list = this.jdbcTemplate.queryForList(
						"SELECT ID FROM formmain_1679 WHERE field0006 =?", MapUtils.getString(map, "pk_dept"));
				if (list.isEmpty()) {
					// 添加数据
					String dataXML = this.freemarkFlowManager
							.fltTemplateIntoString("datasync/orgsync/initDeptDataXML.ftl", map);
					// 可以使用数据模板生成，这样底表事件依然有效
					FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
					FormExport[] formExports = FormUtils.xmlTransformFormExports(dataXML);
					for (FormExport formExport : formExports) {
						formFactory.importBusinessFormData("oa1", "SH_DEPT_DATA_001", formExport, null);
					}
				} else {
					// 更新数据
					String updateSql = this.freemarkFlowManager
							.fltTemplateIntoString("datasync/orgsync/initsql/update_dept_sql.ftl", map);
					int count = this.jdbcTemplate.update(updateSql);
					log.info("更新底表部门数据" + count + "条，\nSQL：" + updateSql);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("NC 数据初始化错误：" + e.getMessage());
		}
	}

	/**
	 * 人员信息初始化
	 */
	public void initNCMember() {
		try {
			SysncPsn sysncPsn0 = new SysncPsn();
			String maxDateSql = this.freemarkFlowManager
					.fltTemplateIntoString("datasync/orgsync/initsql/select_member_maxdate.ftl", null);
			List<Map<String, Object>> maxDate = this.jdbcTemplate.queryForList(maxDateSql);
			if (!maxDate.isEmpty()) {
				Map<String, Object> maxDateMap = maxDate.get(0);
				Map<String, Object> par = new HashMap<>();
				par.put("ts", MapUtils.getString(maxDateMap, "ts"));
				sysncPsn0.setString(JSON.toJSONString(par));
			}
			SysncPsnResponse rs = getISyncServiceStub().sysncPsn(sysncPsn0);
			JSONObject jsonObject = JSONObject.parseObject(rs.get_return());
			JSONArray items = JSON.parseArray(jsonObject.getString("obj"));
			for (Object object : items) {
				Map<String, Object> map = (Map<String, Object>) object;
				List<Map<String, Object>> list = this.jdbcTemplate.queryForList(
						"SELECT ID FROM formmain_1678 WHERE FIELD0001=?", MapUtils.getString(map, "pk_psndoc"));
				if (list.isEmpty()) {
					// 添加数据
					String dataXML = this.freemarkFlowManager
							.fltTemplateIntoString("datasync/orgsync/initMemberDataXML.ftl", map);
					// 可以使用数据模板生成，这样底表事件依然有效
					FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
					FormExport[] formExports = FormUtils.xmlTransformFormExports(dataXML);
					for (FormExport formExport : formExports) {
						formFactory.importBusinessFormData("oa1", "SH_MEMBER_DATA_001", formExport, null);
					}
				} else {
					// 更新数据
					String updateSql = this.freemarkFlowManager
							.fltTemplateIntoString("datasync/orgsync/initsql/update_member_sql.ftl", map);
					int count = this.jdbcTemplate.update(updateSql);
					log.info("更新底表人员数据" + count + "条，\nSQL：" + updateSql);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("人员添加错误：" + e.getMessage());
		}
	}

	/**
	 * 岗位信息初始化
	 */
	public void initNCPost() {
		try {
			SyncPosts syncPosts24 = new SyncPosts();
			String maxDateSql = this.freemarkFlowManager
					.fltTemplateIntoString("datasync/orgsync/initsql/select_post_maxdate.ftl", null);
			List<Map<String, Object>> maxDate = this.jdbcTemplate.queryForList(maxDateSql);
			if (!maxDate.isEmpty()) {
				Map<String, Object> maxDateMap = maxDate.get(0);
				Map<String, Object> par = new HashMap<>();
				par.put("ts", MapUtils.getString(maxDateMap, "ts"));
				syncPosts24.setString(JSON.toJSONString(par));
			}
			SyncPostsResponse rs = getISyncServiceStub().syncPosts(syncPosts24);
			JSONObject jsonObject = JSONObject.parseObject(rs.get_return());
			JSONArray items = JSON.parseArray(jsonObject.getString("obj"));
			for (Object object : items) {
				Map<String, Object> map = (Map<String, Object>) object;
				List<Map<String, Object>> list = this.jdbcTemplate.queryForList(
						"SELECT ID FROM formmain_2357 WHERE field0003=?", MapUtils.getString(map, "pk_post"));
				if (list.isEmpty()) {
					// 添加数据
					String dataXML = this.freemarkFlowManager
							.fltTemplateIntoString("datasync/orgsync/initPostDataXML.ftl", map);
					// 可以使用数据模板生成，这样底表事件依然有效
					FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
					FormExport[] formExports = FormUtils.xmlTransformFormExports(dataXML);
					for (FormExport formExport : formExports) {
						formFactory.importBusinessFormData("oa1", "SH_POST_DATA_001", formExport, null);
					}
				} else {
					// 更新数据
					String updateSql = this.freemarkFlowManager
							.fltTemplateIntoString("datasync/orgsync/initsql/update_post_sql.ftl", map);
					int count = this.jdbcTemplate.update(updateSql);
					log.info("更新底表岗位数据" + count + "条，\nSQL：" + updateSql);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("岗位添加错误：" + e.getMessage());
		}
	}

	/**
	 * 添加部门
	 * 
	 * @return
	 */
	public boolean addDept() {
		log.info("================部门同步添加开始===========================");
		String deptSync = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/SELECT_DEPT_ADDSQL.ftl", null);
		try {
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(deptSync);
			Map<String, V3xOrgDepartment> deptMap = new HashMap<>();
			for (Map<String, Object> map : list) {
				V3xOrgDepartment department = new V3xOrgDepartment();
				department.setIdIfNew();
				System.out.println();
				department.setCode(MapUtils.getString(map, "deptCode"));
				department.setName(MapUtils.getString(map, "deptName"));
				String supCode = MapUtils.getString(map, "supCode") == null ? null : MapUtils.getString(map, "supCode");
				Long supId = 0L;
				if (null != deptMap.get(supCode))
					supId = deptMap.get(supCode).getId();
				else
					supId = this.findDepartmentByCode(supCode);
				department.setSuperior(supId);
				department.setOrgAccountId(this.accountId);
				department.setEnabled(true);
				organizationMessage = this.orgManagerDirect.addDepartment(department);
				log.info("=======kk deptAdd is orgMessage:" + organizationMessage.isSuccess());
			}
			log.info("================= 部门同步添加完成============================");
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			log.info("部门同步添加错误：" + e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
		}
		return false;
	}

	/**
	 * 修改部门
	 * 
	 * @return
	 */
	public boolean updateDept() {
		log.info("================部门同步修改开始==========================");
		String deptSync = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/SELECT_DEPT_UPDSQL.ftl", null);
		try {
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(deptSync);
			for (Map<String, Object> map : list) {
				V3xOrgDepartment department = this.orgManager.getDepartmentById(MapUtils.getLong(map, "ID"));
				department.setName(MapUtils.getString(map, "NAME"));
				department.setSuperior(MapUtils.getLong(map, "supId"));
				department.setEnabled(MapUtils.getString(map, "is_state").equals("1"));
				organizationMessage = this.orgManagerDirect.updateDepartment(department);
				log.info("=======kk deptUpdate is orgMessage:" + organizationMessage.isSuccess());
			}
			log.info("================部门同步修改完成===========================");
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			log.info("部门同步修改错误：" + e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
			e.getStackTrace();
		}
		return false;
	}

	/**
	 * 添加岗位
	 * 
	 * @return
	 */
	public boolean addPost() {
		log.info("================岗位同步添加开始==========================");
		String memberSql = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/SELECT_POST_ADDSQL.ftl", null);
		try {
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(memberSql);
			for (Map<String, Object> map : list) {
				V3xOrgPost post = new V3xOrgPost();
				post.setIdIfNew();
				post.setCode(MapUtils.getString(map, "code"));
				post.setName(MapUtils.getString(map, "name"));
				post.setTypeId(1L);
				post.setOrgAccountId(this.accountId);
				post.setEnabled(true);
				organizationMessage = this.orgManagerDirect.addPost(post);
				log.info("=======kk addPost is orgMessage:" + organizationMessage.isSuccess());
			}
			log.info("================岗位同步添加完成==========================");
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			log.info("岗位同步添加错误：" + e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
		}
		return false;
	}

	/**
	 * 修改岗位
	 * 
	 * @return
	 */
	public boolean updatePost() {
		log.info("================岗位同步修改开始===========================");
		String memberSql = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/SELECT_POST_UPDSQL.ftl", null);
		try {
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(memberSql);
			for (Map<String, Object> map : list) {
				V3xOrgPost post = this.orgManager.getPostById(MapUtils.getLong(map, "ID"));
				post.setName(MapUtils.getString(map, "name"));
				post.setIsDeleted(MapUtils.getString(map, "state").equals("0")); 
				organizationMessage = this.orgManagerDirect.updatePost(post);
				log.info("=========kk updatePost is orgMessage:" + organizationMessage.isSuccess());
			}
			log.info("================岗位同步修改完成===========================");
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			log.info("岗位同步修改错误：" + e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
		}
		return false;
	}

	/**
	 * 添加人员信息
	 * 
	 * @return
	 */
	public boolean addMember() {
		log.info("================人员同步添加开始===========================");
		String memberSql = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/SELECT_MEMBER_ADDSQL.ftl", null);
		try {
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(memberSql);
			for (Map<String, Object> map : list) {
				V3xOrgMember v3xOrgMember = new V3xOrgMember();
				v3xOrgMember.setIdIfNew();
				v3xOrgMember.setOrgAccountId(this.accountId);
				v3xOrgMember.setName(MapUtils.getString(map, "memberName"));
				v3xOrgMember.setCode(MapUtils.getString(map, "memberCode"));
				// gender
				v3xOrgMember.setOrgDepartmentId(
						MapUtils.getLong(map, "deptId") != null ? MapUtils.getLong(map, "deptId") : -1L);
				v3xOrgMember
						.setOrgPostId(MapUtils.getLong(map, "postId") != null ? MapUtils.getLong(map, "postId") : -1L);
				v3xOrgMember.setOrgLevelId(ValueUtils.getConfig().getLong("shkk.defaultLevelId")); // 职务级别
																									// 默认
																									// 科员
				v3xOrgMember.setEnabled(true);

				// 姓名转汉语拼音 之后验证登录名是否存在
				String loginName = isLoginNameCheck(
						HanyuPinyinFormatUtils.getEname(MapUtils.getString(map, "memberName")));
				log.info("原登录名：" + MapUtils.getString(map, "memberName") + ",检查后登录名：" + loginName);
				V3xOrgPrincipal p = new V3xOrgPrincipal(v3xOrgMember.getId(), loginName, "123456");
				v3xOrgMember.setV3xOrgPrincipal(p);
				organizationMessage = this.orgManagerDirect.addMember(v3xOrgMember);

				// 添加 人员密级 PSL_ID为空时不添加人员密级， 否则会出现错误会
				if (MapUtils.getString(map, "PSL_ID") != null) {
					List<Map<String, Object>> queryPMMID = this.jdbcTemplate.queryForList(
							"SELECT * FROM(SELECT PMM_ID FROM PERSON_MEMBER_MAP ORDER BY PMM_ID DESC) WHERE ROWNUM = 1");
					int uuid = 1;
					if (!queryPMMID.isEmpty()) {
						uuid = MapUtils.getInteger(queryPMMID.get(0), "PMM_ID") + 1;
					}
					map.put("uuid", uuid);
					map.put("memberId", v3xOrgMember.getId());
					String sql = this.freemarkFlowManager
							.fltTemplateIntoString("sql/orgSync/INSERT_PERSON_MEMBER_MAP_SQL.ftl", map);
					int count = this.jdbcTemplate.update(sql);
					log.info("=======kk   添加人员密级:" + count + "条");
				}
				// 把人员应户名添加至ip配置表
				map.put("loginName", loginName);
				map.put("uuid", UUIDLong.longUUID());
				String sqlIp = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/INSERT_MEMBER_IP_SQL.ftl",
						map);
				int countIp = this.jdbcTemplate.update(sqlIp);
				log.info("=======kk 添加人员ipip配置表:" + countIp);
				log.info("=======kk memberAdd is orgMessage:" + organizationMessage.isSuccess());
			}
			log.info("================人员同步添加完成===========================");
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			log.info("人员同步添加错误：" + e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
			e.getStackTrace();
		}
		return false;
	}

	/**
	 * 修改人员信息
	 * 
	 * @return
	 */
	public boolean updateMember() {
		log.info("================人员修改添加开始==========================");
		String memberSql = this.freemarkFlowManager.fltTemplateIntoString("sql/orgSync/SELECT_MEMBER_UPDSQL.ftl", null);
		try {
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(memberSql);
			for (Map<String, Object> map : list) {
				log.info("===============\n" + map);
				V3xOrgMember v3xOrgMember = this.orgManager.getMemberById(MapUtils.getLong(map, "ID"));
				v3xOrgMember.setName(MapUtils.getString(map, "memberName"));
				v3xOrgMember.setOrgDepartmentId(
						MapUtils.getLong(map, "deptId") != null ? MapUtils.getLong(map, "deptId") : -1L);
				v3xOrgMember
						.setOrgPostId(MapUtils.getLong(map, "postId") != null ? MapUtils.getLong(map, "postId") : -1L);
				v3xOrgMember.setEnabled(MapUtils.getString(map, "is_state").equals("1"));
				organizationMessage = this.orgManagerDirect.updateMember(v3xOrgMember);

				// 更新人员密级
				String sql = this.freemarkFlowManager
						.fltTemplateIntoString("sql/orgSync/UPDATE_PERSON_MEMBER_MAP_SQL.ftl", map);
				int count = this.jdbcTemplate.update(sql);
				log.info("=======kk 更新人员密级:" + count);
				// 防止出现添加人员时 PSL_ID 为 null，修改时不为 null

				if (count == 0) {
					// 添加 人员密级 PSL_ID为空时不添加 人员密级否则会出现错误会
					if (MapUtils.getString(map, "PSLID") != null) {
						List<Map<String, Object>> queryPMMID = this.jdbcTemplate.queryForList(
								"SELECT * FROM(SELECT PMM_ID FROM PERSON_MEMBER_MAP ORDER BY PMM_ID DESC) WHERE ROWNUM = 1");
						int uuid = 1;
						if (!queryPMMID.isEmpty()) {
							uuid = MapUtils.getInteger(queryPMMID.get(0), "PMM_ID") + 1;
						}
						map.put("uuid", uuid);
						map.put("memberId", v3xOrgMember.getId());
						String sqlLevel = this.freemarkFlowManager
								.fltTemplateIntoString("sql/orgSync/INSERT_PERSON_MEMBER_MAP_SQL.ftl", map);
						int num = this.jdbcTemplate.update(sqlLevel);
						log.info("=======kk   添加人员密级:" + num + "条");
					}
				}
				log.info("=======kk memberAdd is orgMessage:" + organizationMessage.isSuccess());
			}
			log.info("===============人员修改添加完成======================");
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			e.getStackTrace();
			log.info("人员同步修改错误：" + e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
		}
		return false;
	}

	/**
	 * 向会议系统添加组织架构初始化
	 * 
	 * @return
	 */
	public boolean initMeetingOrg() {
		String meetingDeptSql = this.freemarkFlowManager
				.fltTemplateIntoString("datasync/orgsync/initsql/select_meeting_dept_sql.ftl", null);
		String meetingMemberSql = this.freemarkFlowManager
				.fltTemplateIntoString("datasync/orgsync/initsql/select_meeting_member_sql.ftl", null);
		Map<String, Object> sendTOMeeting = Maps.newHashMap();
		try {
			List<Map<String, Object>> deptList = this.jdbcTemplate.queryForList(meetingDeptSql);
			List<Map<String, Object>> userList = this.jdbcTemplate.queryForList(meetingMemberSql);
			sendTOMeeting.put("currentNum", "0");
			sendTOMeeting.put("deptList", MapToLowerCaseUtils.listMapToLower(deptList));
			sendTOMeeting.put("synchTime", DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")); // 当前时间yyyyMMddHHmmss
			sendTOMeeting.put("totalNum", "0");
			sendTOMeeting.put("userList", MapToLowerCaseUtils.listMapToLower(userList));
			log.info("==========>>会议系统推送组织架构：" + JSON.toJSONString(sendTOMeeting));
			Client client = ClientBuilder.newClient();
			WebTarget webTarget = client.target(ValueUtils.getConfig().getString("shkk.MeetingOrgsyncUrl")).path("user")
					.path("synchOrganization");
			String rs = webTarget.request()
					.post(Entity.entity(JSON.toJSONString(sendTOMeeting), MediaType.APPLICATION_JSON), String.class);
			log.info("================人员修改添加完成===========================");
			log.info("=============》人员添加推送结果：" + rs);
			rsMap.put("code", "1000");
			rsMap.put("message", "");
			return true;
		} catch (Exception e) {
			log.info("人员同步修改错误：" + e.getMessage());
			rsMap.put("code", "1001");
			rsMap.put("message", e.getMessage());
			e.getStackTrace();
		}
		return false;
	}

	/**
	 * 根据部门编码查询ID
	 * 
	 * @param supCode
	 *            部门编码
	 * @return accountId or ID
	 */
	private Long findDepartmentByCode(String supCode) {
		if (StringUtils.isEmpty(supCode))
			return this.accountId;
		List<Map<String, Object>> vl = this.jdbcTemplate
				.queryForList("SELECT ID FROM ORG_UNIT WHERE IS_ENABLE = 1 AND IS_DELETED = 0 AND CODE = ?", supCode);
		if (vl.isEmpty())
			return this.accountId;
		return MapUtils.getLong(vl.get(0), "ID");
	}

	/**
	 * 登录名检查
	 * 
	 * @param loginName
	 * @return
	 */
	private String isLoginNameCheck(String loginName) {
		if (StringUtils.isEmpty(loginName))
			return null;
		boolean loginNameFlag = true;
		int num = 1;
		while (loginNameFlag) {
			String loginNameSql = "SELECT LOGIN_NAME FROM ORG_PRINCIPAL  WHERE IS_ENABLE = 1 AND LOGIN_NAME = '"
					+ loginName + "'";
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(loginNameSql);
			if (!list.isEmpty()) {
				loginName += num;
				num++;
			} else {
				loginNameFlag = false;
			}
		}
		return loginName;
	}
	
	/**
	 * 每天同步项目档案底表数据至NC
	 */
	public void syncTONCPro(){
		try {
			log.info("======shkk 项目档案同步至NC 开始==============");
			String sql = this.freemarkFlowManager.fltTemplateIntoString("sql/workOrSkill/SELECT_PRO_SQL.ftl", null);
			List<Map<String, Object>> array = this.jdbcTemplate.queryForList(sql);
			log.info("======shkk 项目档案同步至NC 开始==============\n"+array);
			ISyncProStub iSyncProStub = new ISyncProStub();
			SyncPro syncPro0 = new SyncPro();
			syncPro0.setString(JSONArray.toJSONString(MapToLowerCaseUtils.listMapToLower(array)));
			SyncProResponse rs = iSyncProStub.syncPro(syncPro0 );
			log.info("======shkk 项目档案同步至NC result ："+rs.get_return());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("======shkk 项目档案同步至NC 错误 ："+e.getMessage());
		} 
	}
	
	/**
	 * 每天同步NC资金项目计划
	 */
	public void syncFundPlan(){
		try {
			String maxDateSql = this.freemarkFlowManager
					.fltTemplateIntoString("datasync/orgsync/initsql/select_syncfund_maxdate.ftl", null);
			List<Map<String, Object>> maxDate = this.jdbcTemplate.queryForList(maxDateSql);
			SyncFundPlan syncFundPlan12 = new SyncFundPlan();
			if (!maxDate.isEmpty()) {
				Map<String, Object> maxDateMap = maxDate.get(0);
				Map<String, Object> par = new HashMap<>();
				par.put("ts", MapUtils.getString(maxDateMap, "ts"));
				syncFundPlan12.setString(JSON.toJSONString(par));
			}
			SyncFundPlanResponse rs = getISyncServiceStub().syncFundPlan(syncFundPlan12);
			JSONObject jsonObject = JSONObject.parseObject(rs.get_return());
			JSONArray items = JSON.parseArray(jsonObject.getString("obj"));
			for (Object object : items) {
				Map<String, Object> map = (Map<String, Object>) object;
				List<Map<String, Object>> list = this.jdbcTemplate.queryForList(
						"SELECT ID FROM FORMMAIN_3043 WHERE FIELD0004 =?", MapUtils.getString(map, "fundcode"));
				if (list.isEmpty()) {
					// 添加数据
					String dataXML = this.freemarkFlowManager
							.fltTemplateIntoString("datasync/orgsync/initSyncFundDataXML.ftl", map);
					// 可以使用数据模板生成，这样底表事件依然有效
					FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
					FormExport[] formExports = FormUtils.xmlTransformFormExports(dataXML);
					for (FormExport formExport : formExports) {
						formFactory.importBusinessFormData("oa1", "SH_FUND_0001", formExport, null);
					}
				} else {
					// 更新数据
					String updateSql = this.freemarkFlowManager
							.fltTemplateIntoString("datasync/orgsync/initsql/update_syncfund_sql.ftl", map);
					int count = this.jdbcTemplate.update(updateSql);
					log.info("更新底表部门数据" + count + "条，\nSQL：" + updateSql);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("======shkk 资金计划项目同步 错误 ："+e.getMessage());
		}
	}

	@Override
	public boolean beforeGrabData() {
		// TODO Auto-generated method stub
		log.info("==>> kk 组织架构同步开始 start =============" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		orgSync();
		log.info("==>> kk 组织架构同步结束   end  =============" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		syncTONCPro();
		syncFundPlan();
		return false;
	}

	@Override
	public boolean grabData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean addData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean updateData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deleteData() {
		// TODO Auto-generated method stub
		return false;
	}
}
